import pos, {PosAppGetinIuput} from 'api/pos'
import asssets from 'modules/assets'
import {PosModule} from 'native-modules'
import React, {useEffect} from 'react'
import {
  Image,
  ImageStyle,
  StyleSheet,
  Text,
  TextStyle,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native'
import {commonStyle, themeColors, translateSize} from 'styles'
import {getAuthorization, operate} from 'services/authorization'
import {Toast} from 'components'
import {PosAppBank, PosAppCustomer, PosAppFee, PosGetInCustomer} from 'api/pos'
import {navigate, navigateReplace} from 'services/navigation'
import {PayResult} from 'api/PayResult'
import {getMoneyFen} from 'utils'
import {usePayContext} from 'services/PayContext'

export interface PayButtonProps {
  style?: ViewStyle
  onPress: (type: 'scan' | 'card') => void
  bank: PosAppBank
  customer: PosAppCustomer
  feeList: PosAppFee[]
  money: number
  scene: string
  refId?: string
  fundId: number
  posGetInCustomerList?: PosGetInCustomer[]
}

const PayButton: React.FC<PayButtonProps> = props => {
  const payContext = usePayContext()

  useEffect(() => {
    // console.log('payprops:', props)
  }, [props])
  const handlePaySuccess = (posAppGetin: PosAppGetinIuput, ylResult: string) => {
    // payContext
    // 	.sendDataTest({
    // 		orderInfo: posAppGetin,
    // 		umsInfo: ylResult,
    // 	})
    // return
    //更新数据
    payContext
      .sendData({
        orderInfo: posAppGetin,
        umsInfo: ylResult,
      })
      .then(res => {
        //数据同步完成移除数据
        navigateReplace('PaySuccess', {posAppGetin: res.data, customer: props.customer})
      })
      .finally(() => {
        flag = false
      })
  }
  const handlePayError = (posAppGetin: PosAppGetinIuput) => {
    //移除交易失败数据
    payContext.removeData({orderInfo: posAppGetin})
    pos.posApp.handlePayError(posAppGetin).finally(() => {
      flag = false
    })
  }

  const payCallBack = () => {}
  let flag = false
  const pay = (type: 'scan' | 'card') => {
    if (flag) return
    flag = true
    console.log('22')
    if (props.money === 0) {
      Toast.show('请设置收款金额！')
      flag = false
      return
    }
    if (props.money < 0) {
      Toast.show('收款金额必须大于0！')
      flag = false
      return
    }
    if (props.scene === 'szsk' && !props.refId) {
      Toast.show('请先选择房间！')
      flag = false
      return
    }
    if (!props.bank || JSON.stringify(props.bank) === '{}') {
      Toast.show('请设置入账银行！')
      flag = false
      return
    }

    let posMoney = getMoneyFen(props.money)
    //单位元
    let money = posMoney / 100

    // 1。调后台获取唯一码
    let posAppGetin = {} as PosAppGetinIuput
    posAppGetin.projectId = getAuthorization().project.id
    posAppGetin.scene = props.scene
    posAppGetin.payMode = type
    posAppGetin.erpCustomerId = props.customer.erpId
    posAppGetin.amount = money
    posAppGetin.mac = getAuthorization().mac
    posAppGetin.bankNumber = props.bank.bankNumber
    posAppGetin.bankName = props.bank.bankName
    posAppGetin.posBankId = props.bank.id
    posAppGetin.erpBankId = props.bank.erpBankId
    posAppGetin.refId = props.refId
    posAppGetin.fundId = props.fundId
    posAppGetin.posGetInCustomerList = props.posGetInCustomerList || []
    posAppGetin.getinFeeList = props.feeList.map(fee => {
      return {erpFeeId: fee.erpId, amount: fee.ye}
    })

    let erpCustomerName = props.customer.name
    if (props.posGetInCustomerList && props.posGetInCustomerList.length > 0) {
      erpCustomerName = props.posGetInCustomerList
        .map((posGetInCustomer: PosGetInCustomer) => {
          return posGetInCustomer.customerName
        })
        .join(';')
    }

    pos.posApp
      .addAppGetIn(posAppGetin)
      .then(res => {
        if (res) {
          console.log('22')

          PosModule.payHj(type === 'scan', 0.01, '99999', '周星星', props.bank.bankNumber, '999999')

          // posAppGetin = res
          //存订单id数据
          // payContext.addOrderData(posAppGetin)

          // PosModule.payHj(
          // 	type === 'scan',
          // 	posMoney,
          // 	res.extOrderNo,
          // 	erpCustomerName,
          // 	props.bank.bankNumber,
          // 	posAppGetin.id.toString(),
          // )
          // .then(result => {
          //   console.log(result)
          //   let payResult = JSON.parse(result) as PayResult
          //   if (payResult.resultCode !== '0') {
          //     Toast.show(`支付失败！${payResult.resultCode}:${payResult.resultMsg}`)
          //     handlePayError(res)
          //   } else {
          //     handlePaySuccess(res, result)
          //   }
          // })
          // .catch(err => {
          //   handlePayError(res)
          // })
        } else {
          Toast.show(res.msg || '操作失败，请稍后再试')
          flag = false
        }
      })
      .catch(err => {
        Toast.show(err.msg ? err.msg : '操作失败，请稍后再试' + err)
        flag = false
      })
  }

  const renderPayButton = (type: 'scan' | 'card') => {
    return (
      <TouchableOpacity
        style={styles.payContainer}
        onPress={() => {
          operate()
          pay(type)
        }}>
        <Image
          style={styles.payIcon}
          source={type === 'scan' ? asssets.images.icon_qr_code : asssets.images.icon_bank_card}
        />
        <Text style={styles.payTitle}>{type === 'scan' ? '扫码支付' : '银行卡支付'}</Text>
      </TouchableOpacity>
    )
  }
  return (
    <View style={[commonStyle.containerRow, styles.payRow]}>
      {renderPayButton('scan')}
      {renderPayButton('card')}
    </View>
  )
}

interface PayButtonStyle {
  payRow: ViewStyle
  payContainer: ViewStyle
  payIcon: ImageStyle
  payTitle: TextStyle
}

const styles = StyleSheet.create<PayButtonStyle>({
  payRow: {
    justifyContent: 'space-between',
    paddingHorizontal: translateSize(32),
    paddingVertical: translateSize(30),
  },
  payContainer: {
    width: '44%',
    flexDirection: 'row',
    justifyContent: 'center',
    paddingVertical: translateSize(24),
    borderColor: themeColors.divider,
    borderWidth: 1,
    borderRadius: translateSize(4),
  },
  payIcon: {
    width: translateSize(40),
    height: translateSize(40),
  },
  payTitle: {
    fontSize: translateSize(28),
    color: themeColors.title,
    paddingLeft: translateSize(8),
  },
})

export default PayButton
